<?php

namespace api\modules\backend\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $account;
    public $password;
    public $role;

    const GET_API_TOKEN = 'generate_api_token';

    public function init()
    {
        parent::init();
        $this->on(self::GET_API_TOKEN, [$this, 'onGenerateApiToken']);
    }

    /**
     * @inheritdoc
     * 对客户端表单数据进行验证的rule
     */
    public function rules()
    {
        return [
            [['account', 'password'], 'required'],
            ['password', 'validatePassword'],
        ];
    }

    /**
     * 自定义的密码认证方法
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $this->role = $this->getUser();
            if (!$this->role || !$this->role->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect account or password.');
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'account' => '帐号',
            'password' => '密码',
        ];
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            $this->trigger(self::GET_API_TOKEN);
            return $this->role;
        } else {
            return null;
        }
    }

    /**
     * 根据用户名获取用户的认证信息
     * @return mixed
     */
    protected function getUser()
    {
        if ($this->role === null) {
            $this->role = Role::findByAccount($this->account);
        }

        return $this->role;
    }

    public function onGenerateApiToken()
    {
        if (!Role::apiTokenIsValid($this->role->access_token)) {
            $this->role->generateApiToken();
            $this->role->save(false);
        }
    }
}